/*
 * Copyright (c) 2015 DHC Corporation.
 */
package cn.com.dhc.danlu.widget;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;

/**
 * 不滚动的listView，即全部显示
 *
 * @author MuWei
 * @version 1.00 2015/02/03 新建
 */
public class NoScrollListView extends LinearLayout {

    /**
     * Adapter。
     */
    private BaseAdapter adapter = null;

    /**
     * OnItemClickListener。
     */
    private OnItemClickListener onItemClickListener = null;

    public NoScrollListView (Context paramContext) {
        super (paramContext);
        setOrientation (LinearLayout.VERTICAL);
    }

    public NoScrollListView (Context paramContext, AttributeSet paramAttributeSet) {
        super (paramContext, paramAttributeSet);
        setOrientation (LinearLayout.VERTICAL);
    }

    public BaseAdapter getAdapter () {
        return adapter;
    }

    /**
     * 设置适配器。
     *
     * @param adapter
     *         适配器
     */
    public void setAdapter (BaseAdapter adapter) {
        this.adapter = adapter;
        // 移除所有View
        removeAllViews ();
        // 加载View
        bindLinearLayout ();
    }

    /**
     * 加载Adapter中的View
     */
    public void bindLinearLayout () {
        int count = adapter.getCount ();
        for (int i = 0; i < count; i++) {
            // 获取View
            View v = adapter.getView (i, null, null);
            // 加载View
            addView (v);
        }
    }

    /**
     * 设置条目点击监听。
     *
     * @param l
     *         监听器
     */
    public void setOnItemClickListener (OnItemClickListener l) {
        this.onItemClickListener = l;
        int count = getChildCount ();
        for (int i = 0; i < count; i++) {
            // 获取View
            View v = getChildAt (i);
            // 设置点击事件
            v.setOnClickListener (new ItemClick (this, i));
        }
    }

    /**
     * 刷新画面布局。
     */
    public void refresh () {
        // 适配器更新
        adapter.notifyDataSetChanged ();

        // 移除所有View
        removeAllViews ();
        // 加载View
        bindLinearLayout ();
    }

    /**
     * 屏蔽touch事件的传递,通过父容器判断touch位置
     */
    @Override
    public boolean dispatchTouchEvent (MotionEvent ev) {
        return false;
    }

    public interface OnItemClickListener {
        void onItemClick (NoScrollListView parent, int position);
    }

    private class ItemClick implements View.OnClickListener {
        private NoScrollListView parent;
        private int position;

        ItemClick (NoScrollListView parent, int position) {
            this.parent = parent;
            this.position = position;
        }

        @Override
        public void onClick (View v) {
            onItemClickListener.onItemClick (parent, position);
        }
    }
}